import { Injectable, UnauthorizedException } from '@nestjs/common';
import { CreateClassRoomDto } from './dto/create-class-room.dto';
import { UpdateClassRoomDto } from './dto/update-class-room.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { ClassRoom } from './entities/class-room.entity';
import { In, Repository } from 'typeorm';

@Injectable()
export class ClassRoomsService {
  constructor(
    @InjectRepository(ClassRoom)
    private classRoomRepository: Repository<ClassRoom>,
  ) {}

  create(createClassRoomDto: CreateClassRoomDto) {
    return this.classRoomRepository.save(createClassRoomDto);
  }

  findAll() {
    return this.classRoomRepository.find();
  }

  findOne(id: number) {
    return this.classRoomRepository.findOne({ where: { id } });
  }

  async update(id: number, updateClassRoomDto: UpdateClassRoomDto) {
    const res = await this.findOne(id);
    if (!res.id) {
      return new UnauthorizedException('教室不存在');
    }
    const newRes = this.classRoomRepository.merge(res, updateClassRoomDto);
    return this.classRoomRepository.save(newRes);
  }

  async remove(id: number) {
    const res = await this.findOne(id);
    if (res?.id) {
      return await this.classRoomRepository.remove(res);
    }
    return new UnauthorizedException('学生不存在！');
  }

  // 返回实体
  async returnClassRoomsEntities(ids: number[]) {
    return await this.classRoomRepository.find({
      where: {
        id: In(ids),
      },
    });
  }
}
